import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Divider,
  Tabs,
  Form,
  Icon,
  Modal,
  Table,
  Input,
  Upload,
  Select,
  Button,
  message,
  Popconfirm,
  Switch,
  DatePicker,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import TableComponent from 'components/TableComponent';
import FunctionEdit from 'components/FunctionEdit';
import token from '../../utils/token';
import {env, host} from '../../utils/request'

import styles from './index.less';

const { Option } = Select;
const FormItem = Form.Item;
const {  RangePicker} = DatePicker;

@connect(({ functionSlot, loading }) => ({
  functionSlot,
  loading: loading.models.functionSlot,
}))
@Form.create()
export default class FunctionSlot extends PureComponent {
  state = {
    modalVisible: false,
    isEdit: false,
    editCon:{},
    senFuncParam:{
      current:1,
      pageSize:10,
      sortField:null,
      sortOrder: null,
      source: null,
      startTime:null,
      endTime:null,
      status:null,
      title:null,
    },
    funcStatus:[
      {
        tit:'已上线',
        val:'ON_LINE',
      },
      {
        tit:'待上线',
        val:'WAIT_LINE',
      },
      {
        tit:'已下线',
        val:'UNDER_LINE',
      },
    ],
  };
  componentWillMount() {
    const { senFuncParam } = this.state;
    switch(this.props.location.pathname.split('/')[1]) {
      case 'operatingCenter':
        senFuncParam.source = 'up';
        break;
      case 'operatingCenterForXbeauty':
        senFuncParam.source = 'xbeauty';
        break;
      case 'operatingCenterForXflower':
        senFuncParam.source = 'xflower';
        break;
      case 'operatingCenterForUpoint':
        senFuncParam.source = 'upoint';
        break;
      default:
        break;
    }
  }

  componentDidMount() {
    this.initGetFncList()
  }

  initGetFncList = ()=>{
    const { dispatch } = this.props;
    const {senFuncParam} = this.state
    dispatch({
      type: 'functionSlot/fetchGetFunctionList',
      payload:{
        ...senFuncParam
      }
    });

  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { senFuncParam } = this.state;
    senFuncParam.current=  pagination.current;
    senFuncParam.pageSize = pagination.pageSize;
    this.initGetFncList();
  };
  handleModal =(e)=>{
    this.setState({
      modalVisible: !!e,
    })
    if(!e){
      this.setState({
        editCon: {},
        isEdit: false,
      })
    }

  }
  handleEditFnc = (record)=>{
    this.setState({
      editCon: record,
      isEdit: true,
    })
    this.handleModal(true);
  }


  handleCreateTime =(dates,dateStrings,string) =>{
    this.state.senFuncParam.startTime =dateStrings[0]? moment(dateStrings[0]).format('YYYY-MM-DD HH:mm:ss'): ''
    this.state.senFuncParam.endTime = dateStrings[1]? moment(dateStrings[1]).format('YYYY-MM-DD HH:mm:ss'): '';
  }
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    const {senFuncParam} = this.state;
    senFuncParam.title = null ;
    senFuncParam.status = null;
    senFuncParam.startTimet = null;
    senFuncParam.endTime = null;
    this.initGetFncList();
  };
  handleSearch = e => {
    e.preventDefault();
    const { senFuncParam } = this.state
    const {  form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log(fieldsValue)
      senFuncParam.title = fieldsValue.title? fieldsValue.title: null ;
      senFuncParam.status = fieldsValue.status? fieldsValue.status: null;
      this.initGetFncList();
    });
  };
  renderExtendTable = (record,index) =>{
    const exColumns = [
      {
        title: '序号',
        key: 'sortNo',
        dataIndex: 'sortNo',
      },
      {
        title: '组标题',
        key: 'title',
        dataIndex: 'title',
      },
      {
        title: '图片详情',
        key: 'img',
        dataIndex: 'img',
        render: val => <img src={val} style={{width:40,height:40}} alt=""/>
      },
    ];
    const sorceData = [
      {
        sortNo: 1,
        title: '借款',
        img: record.loanUrl
      },
      {
        sortNo: 2,
        title: '商城',
        img: record.mallUrl
      },
      {
        sortNo: 3,
        title: '消息',
        img: record.messageUrl
      },
      {
        sortNo: 4,
        title: '购物车',
        img: record.cartUrl
      },
      {
        sortNo: 5,
        title: '我的',
        img: record.mineUrl
      },
    ]
    return(
      <Table dataSource={sorceData} columns={exColumns} pagination={false} />
    )
  }

  handleFuncEdit = (e,type) =>{
    const { dispatch } = this.props;
    dispatch({
      type: type ? 'functionSlot/fetchUpdateFunction' : 'functionSlot/fetchAddFunction',
      payload:{
        ...e
      },
      callback:(res)=>{
        message.success(res.message);
        this.initGetFncList();
      }
    });
  }

  handleOnOfflineFunc = (record,type) =>{
    const { dispatch } = this.props;
    dispatch({
      type:'functionSlot/fetchOnOffFunction',
      payload:{ ...{ id:record.id,status:type } },
      callback:(res)=>{
        message.success(res.message);
        this.initGetFncList();
      }
    });
  }
  renderForm(){
    const {form} = this.props
    const { getFieldDecorator } = form;
    const {funcStatus} =this.state
    return(
      <Card bordered={false} style={{marginBottom:20}}>
        <div style={{marginBottom:20}}> <Button icon="plus" onClick={()=>{this.handleModal(true)}}>新建功能槽</Button></div>
        <Form onSubmit={this.handleSearch} >
          <Row style={{marginBottom:12}}  gutter={{ md: 12, lg:24, xl: 48 }}>
            <Col md={6} sm={24}>
              <FormItem label="组标题">
                {getFieldDecorator('title')( <Input  />)}
              </FormItem>
            </Col>
            <Col md={6} sm={24}>
              <FormItem label="状态">
                {getFieldDecorator('status')(<Select >
                  {
                    funcStatus.map((item,i)=>{
                      return  <Option value={item.val} key={i}>{item.tit}</Option>
                    })
                  }
                </Select>)}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <FormItem label="创建时间">
                {getFieldDecorator('createTime')(<RangePicker onChange={this.handleCreateTime} />)}
              </FormItem>
            </Col>
          </Row>
          <Row style={{marginBottom:12}}>
            <Col md={8} sm={24}>
              <Button type="primary" htmlType="submit" >
                查询
              </Button>
              <Button style={{marginLeft:18}} onClick={this.handleFormReset}>
                重置
              </Button>
            </Col>

          </Row>

        </Form>
      </Card>
    )

  }

  render() {
    const {modalVisible,editCon,isEdit,senFuncParam} = this.state;
    const {functionSlot:{funcListData},loading} = this.props
    const columns =[
      {
        title: '序号',
        key: 'sortNo',
        dataIndex: 'title',
        render: (text, record,index) => (
          <a  href="javascript:;" >{index+1}</a>
        )
      },
      {
        title: '组标题',
        key: 'title',
        dataIndex: 'title',
        render: val => `${val}`
      },
      {
        title: '上线时间',
        dataIndex: 'onLineTime',
        render: val => val ? val: '/'
      },
      {
        title: '下线时间',
        dataIndex: 'undeLineTime',
        render: val => val ? val: '/'
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: val => <span>{val=='ON_LINE' ? '已上线': val=='WAIT_LINE' ? '待上线':'已下线'}</span>
      },
      {
        title: '操作',
        dataIndex: 'id',
        key:'id',
        render: (text, record) =>
          <div>
            {
              record.status == 'UNDER_LINE' ? ''
                :
                <span>
                   {
                     record.status =='WAIT_LINE' ?
                       <span>
                         <a href="javascript:;" onClick={() =>{this.handleOnOfflineFunc(record,'ON_LINE')}}>上线</a>
                         <Divider type="vertical" />
                         <a href="javascript:;" onClick={()=>{this.handleEditFnc(record)}}>编辑</a>
                         <Divider type="vertical" />
                         <a href="javascript:;" onClick={() =>{this.handleOnOfflineFunc(record,'UNDER_LINE')}}>下线</a>
                       </span>
                       :''
                   }
                  {
                    record.status =='ON_LINE' ?
                      <a href="javascript:;" onClick={() =>{this.handleOnOfflineFunc(record,'UNDER_LINE')}}>下线</a>
                      : ''
                  }
                </span>
            }
          </div>
      },
    ];
    const uploadProps = {
      url :host[env] + '/user/creditMarket/upload/',
      headers: {
        Authorization: token.get(),
      },
      editCon: editCon,
      isEdit: isEdit,
      source: senFuncParam.source,
      handleFunc: this.handleFuncEdit,
      handleModal: this.handleModal
    }
    return (
      <PageHeaderLayout title="功能槽设置">
        <div>{this.renderForm()}</div>
        <Card bordered={false}>
         <TableComponent
            data={funcListData}
            columns={columns}
            loading={loading}
            onChange={this.handleStandardTableChange}
            expandedRowRender = {this.renderExtendTable}
            rowKey={record => record.id}
          />
        </Card>
       <Modal
          visible={modalVisible}
          onCancel={()=>{this.handleModal(false)}}
          footer={null}
          closable = {false}
          width={700}
          destroyOnClose = {true}
        >
         <FunctionEdit {...uploadProps} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
